//---------------------------------------------------------------
//核心业务类
//create by zhuchentong @ 20170418
//---------------------------------------------------------------
var d1 = require("deviceone");
var App = d1.sm("do_App");
var log = require('util/log');
var router = require('config/router')
var event = require('config/event')
var Bind = require('core/bind')
var Base = require('core/base')
var promise = require('lib/promise')
var dialog = d1.sm("do_Dialog")
var page;

// 扩展js原生对象
require('extend/Array')
require('extend/Date')
require('extend/Object')
require('extend/String')

// 创建核心类
var Controller = d1.Class(Base, function(options, id) {
	Base.initialize.call(this, id);
	// 配置参数对象
	this._config = options.config
	// 页面选项对象
	this._options = options
	// 页面组件列表
	this._component = {}
	// 页面ui对象
	this._ui = {}
	// 页面数据对象
	this._data = options.data
	// 页面方法对象
	this._mehtods = options.methods
	// 创建数据绑定对象
	this._bind = new Bind(id, options.mapping, options.data, options.filter)
	// 初始化数据绑定对象
	this._bind.init()

	// 合并实例方法
	d1.merge(Controller.fz, options.methods)

	// 初始化生命周期监听
	addPageListener.call(this)
	// 加载自定义组件
	loadComponent.call(this)
	// 注册页面ui变量
	registerUI.call(this, options.ui)
	// 初始化事件绑定
	createEventListener.call(this)

})

/**
 * 创建页面控件事件监听
 * 
 * @param eventObj
 * @returns
 */
function createEventListener() {
	var self = this
	var eventObj = this._options.event
	for ( var id in eventObj) {
		var target
		switch (id) {
		case '$page': {
			target = page
		}
			break;
		default: {
			target = this.getUI(id)
		}
		}

		var eventList = eventObj[id]
		for ( var eventName in eventList) {
			var eventHandle = eventList[eventName]
			var handle = function() {
				var _target = target
				var _eventName = eventName
				var _eventHandle = eventHandle
				_target.on(_eventName, function() {
					_eventHandle.apply(self, arguments)
				})
			}
			handle.call(this)
		}
	}
}

/**
 * 添加页面基础事件监听
 * 
 * @returns
 */
function addPageListener() {
	// 主页面事件注册
	if (!page) {
		page = d1.sm('do_Page')
		// 添加页面初始化监听
		addBackListener.call(this)
		// 多次注册事件
		addLoadedListener.call(this, true)
	} else {
		// 子页面事件注册
		addLoadedListener.call(this)
	}

	this._root.on("touch", function() {
		// 点击空白处关闭键盘
		page.hideKeyboard();
	})

}

/**
 * 添加页面初始监听
 * 
 * @param page
 * @returns
 */
function addLoadedListener(isMain) {
	var loaded = this._options.loaded
	if (loaded) {
		var self = this
		if (isMain) {
			page.on('loaded', function() {
				loaded.call(self, page.getData())
			})
		} else {
			loaded.call(self, page.getData())
		}
	}
}

function addBackListener() {
	if (this._config && this._config.back
			&& typeof this._config.back === 'function') {
		var self = this
		page.on('back', function() {
			self._config.back.call(self)
		})

	} else {
		page.on('back', function() {
			App.closePage()
		})
	}
}

/**
 * 加载自定义组件
 * 
 * @returns
 */
function loadComponent() {
	if (this._config && this._config.header) {
		loadHeaderComponent.call(this, this._config.header)
	}
}

/**
 * 加载header组件
 * 
 * @param header
 * @returns
 */
function loadHeaderComponent(header) {
	var header_address = this._root.add("header",
			"source://script/component/header.ui", 0, 0);
	this._component.header = header_address
	var target = this.getUI(header_address)
	target.fire(event.header.loaded, header)
	var self = this
	target.on(event.header.rightTouch, function() {
		if (header && header.right && header.right.handle) {
			header.right.handle.call(self)
		}
	})

}

/**
 * 注册ui组件
 */
function registerUI(params) {
	params = params || {}

	for ( var key in params) {
		var value = params[key]
		try {
			this._ui[key] = this.getUI(value)
		} catch (ex) {

		}
	}
}

// 扩展基础方法
d1.merge(Controller.fz, {
	/**
	 * 进行页面数据刷新
	 */
	refresh : function() {
		this._bind.refresh.apply(this._bind, arguments)
	},
	/**
	 * 更新header信息
	 */
	updateHeader : function(title) {
		if(!this._config){
			this._config = {}
		}
		if(!this._config.header){
			this._config.header = {}
		}
		this._config.header.title = title
		if (this._component.header) {
			var header = this.getUI(this._component.header)
			header.fire(event.header.updateTitle, title)
		}
	},
	getSource : function(key) {
		return this._bind.getSource(key)
	},
	loadReady : function(taskList) {
		if (taskList instanceof Array && taskList.length > 0) {
			var loading = this._root.add("loading",
					"source://script/component/loading.ui", 0, 0);
			this._component.loading = loading
			var target = this.getUI(loading)
			promise.join(taskList).then(function() {
				target.visible = false
			})
			return promise
		}
	}
})

// 扩展基础属性
Object.defineProperties(Controller.fz, {
	// 页面数据对象(只读)
	data : {
		get : function() {
			return this._data
		}
	},
	// 页面方法对象(只读)
	methods : {
		get : function() {
			return this._methods
		}
	},
	// 页面ui对象
	ui : {
		get : function() {
			return this._ui
		}
	}
});

module.exports = function(options) {
	var id = this.__address
	return new Controller(options, id)
}